package com.sz.common.core.service.queue;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-05-22 15:10:00.
 */
public class MemoryQueue<T> implements Queue<T> {

    //链式阻塞队列，可保证多线程的安全
    protected LinkedBlockingQueue<T> innerQueue = null;

    public MemoryQueue() {
        this(Integer.MAX_VALUE);
    }

    public MemoryQueue(int size) {
        innerQueue = new LinkedBlockingQueue<>(size);
    }

    @Override
    public boolean add(T object) { //非阻塞，不会抛出异常
        return this.innerQueue.offer(object);
    }

    @Override
    public T take() {
        try {  //如果队列为空，此处会阻塞，请在独立子线程中调用本方法
            return this.innerQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
